<template>
	<div class="min-h-screen bg-gradient-to-br from-gray-50 via-blue-50 to-indigo-50">
		<!-- 背景装饰 -->
		<div class="fixed inset-0 overflow-hidden pointer-events-none">
			<div
				class="absolute -top-40 -right-40 w-80 h-80 bg-blue-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob">
			</div>
			<div
				class="absolute -bottom-40 -left-40 w-80 h-80 bg-purple-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-2000">
			</div>
			<div
				class="absolute top-40 left-40 w-80 h-80 bg-pink-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-4000">
			</div>
		</div>

		<!-- 主要内容区域 -->
		<div class="container mx-auto px-12 py-10 pt-32 relative z-10">
			<!-- 顶部：返回与标题 -->
			<div class="flex items-center justify-between mb-10">
				<div class="flex items-center gap-4">
					<el-button type="primary" link @click="goBack" class="text-gray-600 hover:text-gray-800 text-lg">
						<el-icon class="mr-2 text-xl">
							<ArrowLeft />
						</el-icon>
						返回班级详情
					</el-button>
					<h1 class="text-4xl font-bold text-gray-900">公告栏</h1>
				</div>
				<el-button type="primary" size="large" @click="showCreateDialog = true"
					class="rounded-full px-6 bg-gradient-to-r from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700 transition-all">
					<el-icon class="mr-2">
						<Plus />
					</el-icon>发布新公告
				</el-button>
			</div>

			<!-- 公告列表 -->
			<div class="bg-white rounded-3xl shadow-xl border border-gray-200 overflow-hidden">
				<div class="p-8">
					<!-- 公告列表 -->
					<div class="space-y-6">
						<div v-for="announcement in announcements" :key="announcement.id"
							class="border border-gray-200 rounded-2xl p-6 hover:shadow-md transition-shadow">
							<div class="flex justify-between items-start mb-4">
								<div>
									<h3 class="text-2xl font-bold text-gray-900">{{ announcement.title }}</h3>
									<p class="text-gray-500 mt-1">
										<span>发布于 {{ formatDate(announcement.createTime) }}</span>
										<span class="mx-2">•</span>
										<span>发布人: {{ announcement.author }}</span>
									</p>
								</div>
								<div class="flex gap-2">
									<el-button type="text" size="small" @click="handleEditAnnouncement(announcement)"
										class="text-blue-600 hover:text-blue-800">
										<el-icon class="mr-1">
											<Edit />
										</el-icon>编辑
									</el-button>
									<el-button type="text" size="small" @click="handleDeleteAnnouncement(announcement)"
										class="text-red-600 hover:text-red-800">
										<el-icon class="mr-1">
											<Delete />
										</el-icon>删除
									</el-button>
								</div>
							</div>
							<div class="text-gray-700 text-lg leading-relaxed">
								{{ announcement.content }}
							</div>
							<div v-if="announcement.attachments && announcement.attachments.length > 0"
								class="mt-4 pt-4 border-t border-gray-100">
								<h4 class="text-gray-700 font-medium mb-2">附件：</h4>
								<div class="flex flex-wrap gap-3">
									<div v-for="(file, index) in announcement.attachments" :key="index"
										class="flex items-center gap-2 bg-gray-50 px-3 py-2 rounded-lg">
										<el-icon class="text-gray-500">
											<Document />
										</el-icon>
										<span class="text-gray-700 text-sm">{{ file.name }}</span>
										<el-button type="text" size="small" class="text-blue-600 p-0 h-auto"
											@click="downloadFile(file.url)">
											下载
										</el-button>
									</div>
								</div>
							</div>
						</div>

						<!-- 空状态 -->
						<div v-if="announcements.length === 0" class="text-center py-20">
							<div class="w-24 h-24 mx-auto mb-6 text-gray-300">
								<el-icon class="text-6xl">
									<Message />
								</el-icon>
							</div>
							<h3 class="text-xl font-medium text-gray-500 mb-2">暂无公告</h3>
							<p class="text-gray-400">点击右上角按钮发布第一条公告吧</p>
						</div>
					</div>

					<!-- 分页 -->
					<div v-if="announcements.length > 0" class="mt-10 flex justify-center">
						<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
							:page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper"
							@size-change="handleSizeChange" @current-change="handleCurrentChange" />
					</div>
				</div>
			</div>
		</div>

		<!-- 发布/编辑公告对话框 -->
		<el-dialog v-model="showCreateDialog" :title="isEditing ? '编辑公告' : '发布新公告'" :width="'600px'"
			:before-close="handleDialogClose">
			<el-form ref="announcementForm" :model="formData" :rules="formRules" label-width="80px">
				<el-form-item label="标题" prop="title">
					<el-input v-model="formData.title" placeholder="请输入公告标题" maxlength="50" show-word-limit />
				</el-form-item>
				<el-form-item label="内容" prop="content">
					<el-input v-model="formData.content" type="textarea" placeholder="请输入公告内容" :rows="6" maxlength="500"
						show-word-limit />
				</el-form-item>
				<el-form-item label="附件">
					<el-upload class="upload-demo" action="/api/upload" :on-success="handleUploadSuccess"
						:on-remove="handleUploadRemove" :file-list="formData.attachments" :limit="3"
						:on-exceed="handleExceed" accept=".doc,.docx,.pdf,.xls,.xlsx,.ppt,.pptx,.jpg,.png">
						<el-button type="primary">点击上传</el-button>
						<template #tip>
							<div class="el-upload__tip text-xs text-gray-500">
								支持上传doc、docx、pdf、xls、xlsx、ppt、pptx、jpg、png格式文件，最多3个
							</div>
						</template>
					</el-upload>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="showCreateDialog = false">取消</el-button>
				<el-button type="primary" @click="submitAnnouncement" :loading="submitting">
					{{ isEditing ? '更新公告' : '发布公告' }}
				</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive,
		computed
	} from 'vue'
	import {
		useRoute,
		useRouter
	} from 'vue-router'
	import {
		ArrowLeft,
		Plus,
		Edit,
		Delete,
		Document,
		Message
	} from '@element-plus/icons-vue'
	import {
		ElMessage,
		ElMessageBox,
		ElForm,
		ElFormItem,
		ElInput,
		ElUpload,
		ElPagination,
		ElDialog,
		ElButton
	} from 'element-plus'

	// 路由相关
	const route = useRoute()
	const router = useRouter()
	const classId = route.params.id

	// 状态管理
	const classInfo = ref({})
	const announcements = ref([])
	const total = ref(0)
	const currentPage = ref(1)
	const pageSize = ref(10)
	const loading = ref(false)
	const submitting = ref(false)
	const showCreateDialog = ref(false)
	const isEditing = ref(false)
	const announcementForm = ref(null)

	// 表单数据
	const formData = reactive({
		id: '',
		title: '',
		content: '',
		attachments: []
	})

	// 表单验证规则
	const formRules = {
		title: [{
				required: true,
				message: '请输入公告标题',
				trigger: 'blur'
			},
			{
				min: 2,
				max: 50,
				message: '标题长度在 2 到 50 个字符',
				trigger: 'blur'
			}
		],
		content: [{
				required: true,
				message: '请输入公告内容',
				trigger: 'blur'
			},
			{
				min: 5,
				max: 500,
				message: '内容长度在 5 到 500 个字符',
				trigger: 'blur'
			}
		]
	}

	// 生命周期
	onMounted(() => {
		fetchClassInfo()
		fetchAnnouncements()
	})

	// 方法
	const goBack = () => {
		router.push(`/class/${classId}`)
	}

	// 获取班级信息
	const fetchClassInfo = async () => {
		try {
			// 模拟API请求
			const mockData = {
				id: classId,
				className: '高一(3)班',
				grade: '高一年级'
			}
			classInfo.value = mockData
		} catch (error) {
			ElMessage.error('获取班级信息失败')
		}
	}

	// 获取公告列表
	const fetchAnnouncements = async () => {
		loading.value = true
		try {
			// 模拟API请求
			const mockData = [{
					id: 1,
					title: '关于下周期中考试的通知',
					content: '下周将进行期中考试，请同学们提前做好复习准备。考试时间为周三至周五，具体安排将另行通知。请各位同学认真复习，争取取得好成绩。',
					createTime: '2023-11-15T08:30:00',
					author: '王老师',
					attachments: [{
						name: '期中考试范围.pdf',
						url: '/files/exam-scope.pdf'
					}]
				},
				{
					id: 2,
					title: '家长会通知',
					content: '本周五晚上7点将召开线上家长会，请各位家长准时参加。会议将总结本学期以来的学习情况，并介绍后续教学安排。',
					createTime: '2023-11-10T14:20:00',
					author: '王老师',
					attachments: []
				}
			]
			announcements.value = mockData
			total.value = mockData.length
		} catch (error) {
			ElMessage.error('获取公告列表失败')
		} finally {
			loading.value = false
		}
	}

	// 格式化日期
	const formatDate = (dateString) => {
		const date = new Date(dateString)
		return date.toLocaleString('zh-CN', {
			year: 'numeric',
			month: '2-digit',
			day: '2-digit',
			hour: '2-digit',
			minute: '2-digit'
		})
	}

	// 分页相关
	const handleSizeChange = (size) => {
		pageSize.value = size
		currentPage.value = 1
		fetchAnnouncements()
	}

	const handleCurrentChange = (page) => {
		currentPage.value = page
		fetchAnnouncements()
	}

	// 发布/编辑公告
	const submitAnnouncement = async () => {
		await announcementForm.value.validate()

		submitting.value = true
		try {
			if (isEditing.value) {
				// 模拟编辑公告API请求
				const index = announcements.value.findIndex(item => item.id === formData.id)
				if (index !== -1) {
					announcements.value.splice(index, 1, {
						...formData,
						createTime: new Date().toISOString(),
						author: '王老师'
					})
				}
				ElMessage.success('公告更新成功')
			} else {
				// 模拟发布公告API请求
				const newAnnouncement = {
					id: Date.now(),
					...formData,
					createTime: new Date().toISOString(),
					author: '王老师'
				}
				announcements.value.unshift(newAnnouncement)
				total.value++
				ElMessage.success('公告发布成功')
			}

			showCreateDialog.value = false
			resetForm()
		} catch (error) {
			ElMessage.error(isEditing.value ? '公告更新失败' : '公告发布失败')
		} finally {
			submitting.value = false
		}
	}

	// 编辑公告
	const handleEditAnnouncement = (announcement) => {
		isEditing.value = true
		formData.id = announcement.id
		formData.title = announcement.title
		formData.content = announcement.content
		formData.attachments = [...announcement.attachments]
		showCreateDialog.value = true
	}

	// 删除公告
	const handleDeleteAnnouncement = async (announcement) => {
		try {
			await ElMessageBox.confirm(
				`确定要删除公告"${announcement.title}"吗？`,
				'确认删除', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}
			)

			// 模拟删除API请求
			announcements.value = announcements.value.filter(item => item.id !== announcement.id)
			total.value--
			ElMessage.success('公告删除成功')
		} catch (error) {
			// 取消删除不做处理
		}
	}

	// 上传相关
	const handleUploadSuccess = (response, file, fileList) => {
		formData.attachments = fileList
		ElMessage.success('文件上传成功')
	}

	const handleUploadRemove = (file, fileList) => {
		formData.attachments = fileList
	}

	const handleExceed = (files, fileList) => {
		ElMessage.warning(`最多只能上传3个文件`)
	}

	// 下载文件
	const downloadFile = (url) => {
		// 模拟文件下载
		ElMessage.success('文件开始下载')
		console.log('下载文件:', url)
	}

	// 重置表单
	const resetForm = () => {
		formData.id = ''
		formData.title = ''
		formData.content = ''
		formData.attachments = []
		isEditing.value = false
		if (announcementForm.value) {
			announcementForm.value.resetFields()
		}
	}

	// 关闭对话框
	const handleDialogClose = () => {
		resetForm()
		showCreateDialog.value = false
	}
</script>

<style scoped>
	.animate-blob {
		animation: blob-morph 8s linear infinite;
	}

	.animation-delay-2000 {
		animation-delay: 2s;
	}

	.animation-delay-4000 {
		animation-delay: 4s;
	}

	@keyframes blob-morph {
		0% {
			transform: scale(1) translate(0, 0);
		}

		25% {
			transform: scale(1.1) translate(20px, -20px);
		}

		50% {
			transform: scale(0.9) translate(0, 20px);
		}

		75% {
			transform: scale(1.05) translate(-20px, 10px);
		}

		100% {
			transform: scale(1) translate(0, 0);
		}
	}
</style>